package com.self.console.web.controller.back.common;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.self.console.constant.enums.SystemConfigKey;
import com.self.console.dto.AdminDto;
import com.self.console.persistence.model.SysConfig;
import com.self.console.service.system.SysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sangame.sow.ssh.annotation.NotLogin;
import com.sangame.sow.ssh.orm.hibernate.support.JsonWrapper;
import com.sangame.sow.ssh.service.result.Result;
import com.sangame.sow.ssh.web.support.ExecuteResult;
import com.sangame.sow.utils.IpUtils;
import com.sangame.sow.utils.RandomCodeMaker;

/**
 * 用户登录
 */
@Controller
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@RequestMapping("/back/common")
public class LoginController extends BackController {

	private final static Logger LOG = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private SysConfigService sysConfigService;
	
	@NotLogin
	@RequestMapping(value="login.htm", method=RequestMethod.GET)
	public String login(ModelMap model) {
		SysConfig openSnCheck = sysConfigService.findByKey(SystemConfigKey.CHECK_AUTH_CODE.getValue());
		model.addAttribute("openSnCheck", openSnCheck);
		return LOGIN_PAGE;
	}
	
	@NotLogin
	@RequestMapping(value="doLogin.htm", method=RequestMethod.POST)
	public @ResponseBody JsonWrapper<Object> doLogin(@ModelAttribute("adminDto") AdminDto adminDto, HttpServletRequest request) throws UnsupportedEncodingException {
		JsonWrapper<Object> result = null;
		try {
			if (adminDto == null) {
				return new JsonWrapper<Object>(false, "用户不存在");
			}
			String ip = IpUtils.getClientIp(request);
			String authCode = (String)getSessionAttribute(AUTH_CODE);
			Result _result = adminService.login(adminDto, authCode, ip);
			if(_result.isSuccess()){
				AdminDto user = (AdminDto)_result.getDefaultModel();
				setCurrentSession(user);
			}
			result = new JsonWrapper<Object>(_result.isSuccess(), _result.getResultCode().getMessage(), _result.getModels().get("flag"));
		} catch (Exception e) {
			result = new JsonWrapper<Object>(false, "登录失败，请联系管理员");
			LOG.error("登录出现异常", e);
		}
		return result;
	}
	
	@NotLogin
	@RequestMapping(value="authCode.htm", method=RequestMethod.GET)
	public void authCode(HttpServletResponse response) throws IOException {
		response.setContentType(MediaType.IMAGE_JPEG_VALUE);
		RandomCodeMaker authCode = RandomCodeMaker.getInstance();
		response.getOutputStream().write(authCode.getImageStream().toByteArray()); //取得带有随机字符串的图片   
        setSessionAttribute(AUTH_CODE, authCode.getString());//取得随机字符串放入HttpSession
	}
	
	@NotLogin
	@RequestMapping(value="jump.htm", method=RequestMethod.GET)
	public String jump(ExecuteResult result, ModelMap model) {
		model.addAttribute("result", result);
		return SHOW_MSG_PAGE;
	}
	
	@RequestMapping("logout.htm")
	public String logout(ModelMap model) {
		getSession().invalidate();
		SysConfig openSnCheck = sysConfigService.findByKey(SystemConfigKey.CHECK_AUTH_CODE.getValue());
		model.addAttribute("openSnCheck", openSnCheck);
		return LOGIN_PAGE;
	}
	
}
